<?php

namespace Module\Admin;

use Manager\Category as Manager;
use W3\Html;
use W3\Exception;

!defined('W3_ROOT_DIR') AND exit;

/**
 * 编辑分类组件
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Category extends Manager
{
    /**
     * 初始化
     *
     * @access protected
     * @return void
     */
    protected function init()
    {

        # 必须为编辑员以上权限
        $this->auth->check('editor');
		
		# 定义变量默认数据
        $this->parameter([

			# 设置主体
			'main' => 'admin.category',
		
			# 操作列表
		    'operate'=> [
			    'selectall'=>[
				    'name'=>__('全选'),
					'data-selectall'
				], 
				'delete'=>[
				    'name'=>__('删除'),
					'data-confirm'=>__('删除不可恢复，确定删除？'),
					'href'=>$this->adminUrl('category', 'delete', false)
				]
			]
			
		], true);
		
	}

    /**
     * 绑定动作
     *
     * @access public
     * @return void
     */
    public function action()
    {
		$this->on(!$this->request->action || $this->request->is('action=index'))->index();
		$this->on($this->request->is('action=edit'))->edit();
		$this->on($this->request->isPost() && $this->request->is('action=edit'))->update();
		$this->on($this->request->is('action=add'))->edit();
		$this->on($this->request->isPost() && $this->request->is('action=add'))->add();
		$this->on($this->request->isPost() && $this->request->is('action=delete'))->delete();		
    }

    public function index()
    {
		$this->stack = $this->widget('Category\Rows')->export();

		/** 输出内容 */
		$this->layout->set($this->categoryList(), 'body');

		$this->view();
    }

    public function categoryList()
    {
        if ($this->have()) {
			$table = Html::table();
			$table->thead->preppend($this->operate(false));
			$table->thead->preppend('
                <colgroup>
				    <col width="3%" />
					<col width="3%" />
                    <col width="70%" />
                    <col />
                </colgroup>
			');
			$table->head([
			   '',
			   '',
			    __('名称'),
				__('缩略名'),
			]);
			while ($this->next()){
			    $table->body([
				    Html::checkbox('mid', [$this->mid=>'']),
					'<a class="badge badge-md badge-pill badge-primary-soft mr-2" href="'.$this->adminUrl('post', 'category=' . $this->mid, false).'">'.$this->count.'</a>',
				    '<span class="text-muted">'.($this->level ? '&nbsp;&nbsp;&nbsp;&nbsp;|--':'') . str_repeat('--', $this->level>-1 ? $this->level : ''). '</span> <a href="' .$this->adminUrl('category/edit', 'mid=' . $this->mid, false).'">'.$this->name.'</a>&nbsp;&nbsp;&nbsp;<a class="text-muted" target="_blank" href="'.$this->permalink.'"><svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-link-2"><path d="M15 7h3a5 5 0 0 1 5 5 5 5 0 0 1-5 5h-3m-6 0H6a5 5 0 0 1-5-5 5 5 0 0 1 5-5h3"></path><line x1="8" y1="12" x2="16" y2="12"></line></svg></a>',
					$this->alias
				]);
			}

			$html = $table->wrap(Html::form()->removeClass('w3-form'))->render();
		} else {
			$html = '<h6>'.__('内容为空').'</h6>';
		}

		return $html;
	}

    /**
     * 增加/编辑分类
     *
     * @access public
     * @return void
     */
    public function edit()
    {
		
        if ($this->request->mid) {

            /** 按category查询 */
            $this->db
				->select()
		        ->from('table.metas')
			    ->where('table.metas.type = ? and table.metas.mid = ?', 'category', $this->request->filter('int')->mid)
			    ->limit(1)
			    ->fetch([$this, 'push']);

            if (!$this->have()) {
				
				throw new Exception(__('分类不存在'), 404);
            }
        }
		
        /** 更新模式 */
        if ($this->mid) {
			$this->parameter->title = __('编辑分类: %s', [$this->name]);
        } else {
			$this->parameter->title = __('增加分类');
		}
		
		/** 输出内容 */
		$this->layout->set($this->form(), 'body');
		
		$this->view();
    }

    /**
     * 增加分类
     *
     * @access public
     * @return void
     */
    public function add()
    {
		$form = $this->form();
			
		/** 验证格式 */
        if ($form->validate()) {
            $this->goBack();
        }
				
		/** 取出数据 */
        $category = $this->request->from(array_keys($form->getInputs()));
		$category['type'] = 'category';
		$category['order'] = intval($category['order']) >= 0 ? intval($category['order']) : 99;
				
		$mid = $this->addCategory($category);
		
        $this->db
		    ->select()
		    ->from('table.metas')
		    ->where('table.metas.type = ? and table.metas.mid = ?', 'category', $mid)
			->fetch([$this, 'push']);
			
        /** 提示信息 */
       $this->notice(__('分类 %s 增加成功', [$this->name]));
	   
	   $this->redirect($this->adminUrl('category', false));
	}

    /**
     * 更新分类
     *
     * @access public
     * @return void
     */
    public function update()
    {
		$form = $this->form();
			
		/** 验证格式 */
        if ($form->validate()) {
            $this->goBack();
        }
				
		/** 取出数据 */
        $category = $this->request->from(array_keys($form->getInputs()));
		$category['type'] = 'category';
		$category['order'] = intval($category['order']) >= 0 ? intval($category['order']) : 99;

		$this->updateCategory($this->mid, $category);

        /** 提示信息 */
       $this->notice(__('分类 %s 更新成功', [$this->name]));
	   
	   $this->redirect($this->adminUrl('category', false));
	}

    /**
     * 删除分类
     *
     * @access public
     * @return void
     */
    public function delete()
    {
        $mids = $this->request->filter('int')->getArray('mid');
        $deleteCount = 0;

        foreach ($mids as $mid) 
		{
		    if($this->deleteCategory($mid)){ 
				$deleteCount++;
			}
        }
			
        /** 设置提示信息 */
        $this->notice(
		    $deleteCount > 0 
			    ? __('分类已经删除') 
			    : [__('没有分类被删除, 可能的原因'), __('1: 分类不存在'), __('2: 分类中有内容, 不允许删除分类'), __('3: 分类有下级分类, 不允许删除分类')], 
			
			$deleteCount > 0 ? 'success' : 'notice'
		);
		
		$this->goBack();
	}
}
